#include "webserver.h"
#include "custom_handle.h"
#include "cJSON.h"
#include <stdbool.h>
#include "msg_queue_peer.h"

// 设备映射表定义
// 使用显式类型转换确保类型安全
const DeviceInfo deviceControlMap[] = {
    // STM32设备
    {"light_bedroom", "1", 304},
    {"light_livingroom", "1", 305},
    {"air_purifier", "1", 306},
    // Modbus设备
    {"air_switch", "2", 101},
    {"humidifier", "2", 103},
    {"curtain", "2", 104},
    {"robot_vacuum", "2", 105},
    {"washing_machine", "2", 106},
    {NULL, NULL, 0} // 结束标记
};

int send_device_message(int device_key, int action) {
    msgbuf msg;
    msg.mtype = 1; // 固定消息类型
    
    // 按照图片格式存储为 "key+action"
    snprintf(msg.mdata, sizeof(msg.mdata), "%d+%d", device_key, action);
    
    printf("[DEBUG] 发送消息: type=%ld data=%s\n", msg.mtype, msg.mdata);
    
    if (msg_queue_send("topic", &msg, sizeof(msg), 0) < 0)
        {
            printf("命令发送失败\n");
            return -1;
        }
    return 0;
}

int hardware_control(int device_key, int action) {
    printf("控制设备: key=%d action=%d\n", device_key, action);
    return send_device_message(device_key, action);
}

int get_hardware_status(int device_key) {
    msgbuf msg;
    
    // 非阻塞接收消息
    if (msgrcv(msgid, &msg, sizeof(msg.mdata), device_key, IPC_NOWAIT) > 0) {
        int key, status;
        if (sscanf(msg.mdata, "%d+%d", &key, &status) == 2) {
            if (key == device_key) {
                printf("解析成功: %s → 设备%d=%s\n", 
                      msg.mdata, key, status ? "ON" : "OFF");
                return status;
            }
        }
    }
    
    printf("[模拟值] 设备 %d 状态\n", device_key);
    return rand() % 2; // 返回模拟值
}

int handle_string_control(int sock, const char *command) {
    printf("收到控制命令: %s\n", command);
    
    // 解析格式: type+key+action (如 "2+101+1")
    int key, action;
    if (sscanf(command, "%d+%d", &key, &action) != 2) {
        printf("解析失败！命令格式应为 key+action\n");
        send_response(sock, 400, "text/plain", "错误：格式应为 key+action");
        return -1;
    }

    printf("解析结果:key=%d, action=%d\n", 
            key, action);

    // 执行硬件控制
    int result = hardware_control(key, action);

    // 返回响应
    char response[64];
    snprintf(response, sizeof(response), "控制结果: %s (设备键值=%d)", 
             result ? "成功" : "失败", key);
    send_response(sock, result ? 200 : 500, "text/plain", response);
    
    return result;
}

float get_sensor_data(const char *type) {
    if (!g_shm_ptr) return 0.0;
    
    char *ptr = NULL;
    if (strcmp(type, "temp") == 0) {
        ptr = strstr(g_shm_ptr, "temperature:");
    } else if (strcmp(type, "hum") == 0) {
        ptr = strstr(g_shm_ptr, "humidity:");
    }
    
    return ptr ? atof(ptr + (strcmp(type, "temp") ? 9 : 12)) : 0.0;
}

int handle_get(int sock, const char *input) {
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, "temperature", get_sensor_data("temp"));
    cJSON_AddNumberToObject(json, "humidity", get_sensor_data("hum"));
    
    char *json_str = cJSON_Print(json);
    send_response(sock, 200, "application/json", json_str);
    
    cJSON_Delete(json);
    free(json_str);
    return 0;
}

void handle_device_status(int sock) {
    cJSON *json = cJSON_CreateObject();
    cJSON *devices = cJSON_CreateObject();
    cJSON_AddItemToObject(json, "devices", devices);

    // 遍历所有设备获取状态
    for (const DeviceInfo *dev = deviceControlMap; dev->device_id != NULL; dev++) {
        cJSON *device = cJSON_CreateObject();
        cJSON_AddBoolToObject(device, "isOn", get_hardware_status(dev->key));
        cJSON_AddStringToObject(device, "type", dev->type);
        cJSON_AddItemToObject(devices, dev->device_id, device);
    }

    char *json_str = cJSON_Print(json);
    send_response(sock, 200, "application/json", json_str);
    
    cJSON_Delete(json);
    free(json_str);
}